package io.kiki.sba.registry.server.clientInterface.remoting.handler;

import io.kiki.sba.registry.api.Channel;
import io.kiki.sba.registry.common.model.client.pb.MetaRegister;
import io.kiki.sba.registry.common.model.store.AppRevision;
import io.kiki.sba.registry.core.model.RegisterResponse;
import io.kiki.sba.registry.server.clientInterface.converter.pb.AppRevisionConvertor;
import io.kiki.sba.registry.server.clientInterface.converter.pb.RegisterResponseConvertor;
import io.kiki.sba.registry.server.shared.remoting.RemotingHelper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


public class MetadataRegisterPbHandler extends AbstractClientMetadataRequestHandler<MetaRegister> {
    private static final Logger logger = LoggerFactory.getLogger(MetadataRegisterPbHandler.class);

    @Override
    public Object doHandle(Channel channel, MetaRegister request) {
        RegisterResponse registerResponse = new RegisterResponse();
        AppRevision appRevision = AppRevisionConvertor.convert2Java(request);
        appRevisionHandlerStrategy.handleAppRevisionRegister(appRevision, registerResponse, channel != null ? channel.getRemoteAddress().toString() : StringUtils.EMPTY);

        return RegisterResponseConvertor.convert2Pb(registerResponse);
    }

    @Override
    public Class interest() {
        return MetaRegister.class;
    }

    @Override
    protected void logRequest(Channel channel, MetaRegister request) {
        if (logger.isInfoEnabled()) {
            StringBuilder sb = new StringBuilder(256);
            sb.append("[").append(this.getClass().getSimpleName()).append("] ");
            sb.append("Remote:").append(RemotingHelper.getChannelRemoteAddress(channel)).append(" Revision: ").append(request.getRevision());
            logger.info(sb.toString());
        }
    }
}
